from django.contrib.auth.hashers import check_password

from auther.models import AdminUser
from utils.token import Token


def login(username, password):
    return_data = {'code': "", "msg": ""}
    account = AdminUser.objects.filter(username=username).values("username", "password", "account", "is_superuser","id")
    if account.exists():
        pwd_check = check_password(password, account[0]['password'])
        if pwd_check:
            admin_token = Token()
            admin_token.KEY = account[0]['id']
            set_token = admin_token.create_token()
            return_data['code'] = 200
            return_data['msg'] = "登录成功"
            return_data['data'] = {}
            return_data['data']['token'] = set_token
            return return_data
        else:
            return_data['code'] = 401
            return_data['msg'] = "密码错误"
    else:
        return_data['code'] = 401
        return_data['msg'] = "用户名不存在"
    return return_data

